// Pinia状态管理
import { defineStore } from 'pinia'

// 用户模块
export const useUserStore = defineStore('user', {
  state: () => ({
    token: uni.getStorageSync('token') || '',
    userInfo: uni.getStorageSync('userInfo') || null
  }),
  
  actions: {
    // 更新token
    updateToken(token) {
      this.token = token
      uni.setStorageSync('token', token)
    },
    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = userInfo
      uni.setStorageSync('userInfo', userInfo)
    },
    // 清除用户信息
    clearUserInfo() {
      this.token = ''
      this.userInfo = null
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
    },
    // 登录动作
    login(userInfo) {
      // 这里是登录逻辑，实际开发中需要通过API请求登录
      return new Promise((resolve) => {
        setTimeout(() => {
          // 模拟登录成功
          const token = 'mock_token'
          this.updateToken(token)
          this.updateUserInfo(userInfo)
          resolve({ code: 0, message: '登录成功' })
        }, 1000)
      })
    },
    // 登出动作
    logout() {
      this.clearUserInfo()
      // 跳转到登录页
      uni.redirectTo({
        url: '/pages/login/index'
      })
    }
  },
  
  getters: {
    // 是否已登录
    isLogin: (state) => !!state.token
  }
})

// 血糖记录模块
export const useBloodSugarStore = defineStore('bloodSugar', {
  state: () => ({
    records: uni.getStorageSync('bloodSugarRecords') || [],
    statistics: null,
    loading: false
  }),
  
  actions: {
    // 设置记录列表
    setRecords(records) {
      this.records = records
      uni.setStorageSync('bloodSugarRecords', records)
    },
    
    // 添加血糖记录
    addRecord(record) {
      this.records.unshift(record)
      uni.setStorageSync('bloodSugarRecords', this.records)
    },
    
    // 删除血糖记录
    deleteRecord(id) {
      const index = this.records.findIndex(item => item.id == id)
      if (index !== -1) {
        this.records.splice(index, 1)
        uni.setStorageSync('bloodSugarRecords', this.records)
      }
    },
    
    // 更新血糖记录
    updateRecord({ id, record }) {
      const index = this.records.findIndex(item => item.id == id)
      if (index !== -1) {
        this.records[index] = { ...this.records[index], ...record }
        uni.setStorageSync('bloodSugarRecords', this.records)
      }
    },
    
    // 设置统计数据
    setStatistics(statistics) {
      this.statistics = statistics
    },
    
    // 设置加载状态
    setLoading(loading) {
      this.loading = loading
    },
    
    // 加载血糖记录
    loadBloodSugarRecords(records) {
      this.setRecords(records)
    }
  },
  
  getters: {
    // 按日期分组的记录
    recordsByDate: (state) => {
      const result = {}
      state.records.forEach(record => {
        const date = record.date.split(' ')[0]  // 提取日期部分
        if (!result[date]) {
          result[date] = []
        }
        result[date].push(record)
      })
      return result
    },
    
    // 按类型分组的记录
    recordsByType: (state) => {
      const result = {}
      state.records.forEach(record => {
        if (!result[record.type]) {
          result[record.type] = []
        }
        result[record.type].push(record)
      })
      return result
    },
    
    // 最近一次记录
    latestRecord: (state) => {
      if (state.records.length === 0) return null
      
      // 按时间排序
      const sortedRecords = [...state.records].sort((a, b) => {
        return new Date(b.datetime) - new Date(a.datetime)
      })
      
      return sortedRecords[0]
    },
    
    // 今日记录
    todayRecords: (state) => {
      const today = new Date().toISOString().split('T')[0]
      return state.records.filter(record => record.date === today)
    },
    
    // 今日平均值
    todayAverage: (state) => {
      const todayRecords = state.todayRecords
      if (todayRecords.length === 0) return 0
      
      const sum = todayRecords.reduce((total, record) => total + record.value, 0)
      return sum / todayRecords.length
    }
  }
})

// 提醒模块
export const useReminderStore = defineStore('reminder', {
  state: () => ({
    reminders: uni.getStorageSync('reminders') || []
  }),
  
  actions: {
    // 更新提醒列表
    updateReminders(reminders) {
      this.reminders = reminders
      uni.setStorageSync('reminders', reminders)
    },
    
    // 添加提醒
    addReminder(reminder) {
      this.reminders.push(reminder)
      uni.setStorageSync('reminders', this.reminders)
    },
    
    // 删除提醒
    deleteReminder(id) {
      const index = this.reminders.findIndex(item => item.id == id)
      if (index !== -1) {
        this.reminders.splice(index, 1)
        uni.setStorageSync('reminders', this.reminders)
      }
    },
    
    // 更新提醒
    updateReminder({ id, reminder }) {
      const index = this.reminders.findIndex(item => item.id == id)
      if (index !== -1) {
        this.reminders[index] = { ...this.reminders[index], ...reminder }
        uni.setStorageSync('reminders', this.reminders)
      }
    },
    
    // 切换提醒状态
    toggleReminder({ id, active }) {
      const index = this.reminders.findIndex(item => item.id == id)
      if (index !== -1) {
        this.reminders[index].active = active
        uni.setStorageSync('reminders', this.reminders)
      }
    }
  },
  
  getters: {
    // 按类型分组的提醒
    remindersByType: (state) => {
      const result = {
        medicine: [],
        bloodSugar: [],
        exercise: []
      }
      
      state.reminders.forEach(reminder => {
        if (result[reminder.type]) {
          result[reminder.type].push(reminder)
        }
      })
      
      return result
    },
    
    // 今日提醒
    todayReminders: (state) => {
      const today = new Date()
      const dayOfWeek = today.getDay() || 7 // 0是周日，转换为7
      
      return state.reminders.filter(reminder => {
        // 启用状态的提醒
        if (!reminder.active) return false
        
        // 每天重复或一次性提醒
        if (reminder.repeat === 'daily' || reminder.repeat === 'once') {
          return true
        }
        
        // 每周重复，检查今天是否在重复日期内
        if (reminder.repeat === 'weekly' && reminder.repeatDays.includes(dayOfWeek)) {
          return true
        }
        
        return false
      })
    },
    
    // 最近的提醒
    nextReminder: (state) => {
      const todayReminders = state.todayReminders
      if (todayReminders.length === 0) return null
      
      const now = new Date()
      const currentHour = now.getHours()
      const currentMinute = now.getMinutes()
      
      // 筛选出今天还未触发的提醒
      const upcomingReminders = todayReminders.filter(reminder => {
        const [hour, minute] = reminder.time.split(':').map(Number)
        return (hour > currentHour) || (hour === currentHour && minute > currentMinute)
      })
      
      if (upcomingReminders.length === 0) return null
      
      // 按时间排序，找出最近的一个
      return upcomingReminders.sort((a, b) => {
        const [hourA, minuteA] = a.time.split(':').map(Number)
        const [hourB, minuteB] = b.time.split(':').map(Number)
        
        if (hourA !== hourB) {
          return hourA - hourB
        }
        return minuteA - minuteB
      })[0]
    }
  }
}) 